<template>
  <div class="content-box">
    <div class="content" v-loading="loading">
      <!-- 数据显示区域 -->
      <div class="data_place">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="80px"
        >
          <el-form-item label="查询时间" prop="dateRange">
            <el-date-picker
              :style="{
                width: device === 'mobile' ? '280px' : '355px',
                marginRight: '20px',
              }"
              clearable
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              value-format="yyyy-MM-dd"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              plain
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <!-- 图表显示区域 -->
      <div class="chart_place">
        <div
          :class="[
            'chart_item',
            device === 'desktop' ? 'oneEqualPartsPc' : 'oneEqualPartsMobile',
          ]"
          ref="inAndExpChart"
        ></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import * as echarts from "echarts";
import moment from "moment";

import { querySysInAndExpCake } from "@/api/inAndExpCount/SysInAndExpCount";
export default {
  name: "sysInAndExpCount",
  data() {
    return {
      // 查询参数
      queryParams: {},
      // 时间范围
      dateRange: [],
      loading: false,
      // 图标配置
      chartOptions: {
        title: {
          text: "系统收支饼图",
          left: "right",
        },
        tooltip: {
          // 悬停触发类型
          trigger: "item",
        },
        legend: {
          // 图例位置设置
          orient: "vertical",
          left: "left",
        },
        series: [
          {
            name: "收支情况",
            type: "pie", // 饼图类型
            minAngle: 1, // 最小扇区角度（单位为度），默认是 0
            radius: "50%", // 饼图半径为容器宽度的一半
            data: [
              // 饼图的数据源
            ],
            emphasis: {
              // 鼠标悬停时的高亮样式
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      },
      // 数据映射对象
      dataMappObj: {
        upMoney: {
          label: "上游结算",
          sort: 1,
        },
        downMoney: {
          label: "下游结算",
          sort: 2,
        },
        changeMoney: {
          label: "修正金额",
          sort: 3,
        },
        lastMoney: {
          label: "最终毛利润",
          sort: 4,
        },
      },
    };
  },
  computed: {
    ...mapGetters(["device"]),
  },
  created() {
    this.init();
  },
  mounted() {
    this.initChart();
  },
  methods: {
    // 初始化图表
    initChart() {
      // 客户状态图表实例初始化
      this.inAndExpChart = echarts.init(this.$refs.inAndExpChart);
      this.inAndExpChart.setOption(this.chartOptions);
      window.addEventListener("resize", this.resizeChart);
    },
    // 窗口缩放时重置图表
    resizeChart() {
      this.inAndExpChart && this.inAndExpChart.resize();
      // 如果是移动端不设置标题
      if (this.device === "mobile") {
        this.$set(this.chartOptions, "title", {
          text: "系统收支饼图",
          left: "right",
        });
      } else {
        this.$set(this.chartOptions, "title", {
          text: "系统收支饼图",
          left: "center",
        });
      }
      // 强制更新图表配置
      this.inAndExpChart.setOption(this.chartOptions, true);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 完全重置到初始状态
      this.$set(this, "queryParams", {});
      this.init();
    },
    init() {
      // 设置默认时间
      this.$set(this, "dateRange", [
        moment().format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD"),
      ]);
      this.getList();
    },
    // 获取数据集
    getDataArray(data) {
      const arr = Object.entries(data)
        .map((pre) => {
          let [key, value] = pre;
          if (this.dataMappObj[key]) {
            return {
              name: this.dataMappObj[key].label + " " + value,
              value: Math.abs(value), // 转为正数(饼图只显示非负数)
              originalValue: value, // 保留原始值
              label: {
                show: true,
                position: "outside",
                color: value >= 0 ? "green" : "red", // 设置文字颜色
                fontSize: this?.device === "desktop" ? 16 : 12,
                // formatter: (params) => {// 可以自定label的显示内容
                //   let reg= new RegExp(`(${value})`,'gi')
                //   return `${params.name.replace(reg,'')}${value}`; // 使用原始值
                // },
              },
            };
          }
        })
        .filter((item) => item != undefined);
      return arr;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      if (this.dateRange?.length) {
        this.queryParams.timeStart = this.dateRange[0];
        this.queryParams.timeEnd = this.dateRange[1];
      } else {
        delete this.queryParams.timeStart;
        delete this.queryParams.timeEnd;
      }
      querySysInAndExpCake(this.queryParams).then((res) => {
        if (res.code == 200) {
          let sourceList = this.getDataArray(res?.data);
          // 处理数据集
          this.$set(this.chartOptions.series[0], "data", sourceList);
          console.log(this.chartOptions);
          if (this.device === "mobile") {
            this.$set(this.chartOptions, "title", {
              text: "系统收支饼图",
              left: "right",
            });
          } else {
            this.$set(this.chartOptions, "title", {
              text: "系统收支饼图",
              left: "center",
            });
          }
          // 设置图例文字大小
          this.$set(this.chartOptions.legend, "textStyle", {
            fontSize: this?.device === "desktop" ? 16 : 12, // 设置图例文字大小
          });
          // 强制更新图表配置
          this.inAndExpChart.setOption(this.chartOptions, true);
        }
        this.loading = false;
      }).catch((err) => {
          setTimeout(() => {// 延迟2s后自动取消加载状态
            this.loading = false;
          }, 2000);
      })
    },
  },
};
</script>

<style scoped lang='scss'>
.content {
  background-color: #fff;
  // height: 100%;
  padding: 20px;
  border-radius: 6px;
  .data_place {
    padding-bottom: 20px;
    border-bottom: 1px solid #efefef;
  }
  .chart_place {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding-top: 20px;
    .chart_item {
      box-shadow: 0 4px 6px #d1cfcf;
      filter: drop-shadow(0px 0px 3px #d0d0d0);
      border-radius: 6px;

      flex: 1 1 100%; // 每个子盒子占 100% 的宽度，最多 1 个子盒子一行
      max-width: 100%; // 最大宽度为 100%
    }
    // 一等分PC样式
    .oneEqualPartsPc {
      height: calc(100vh - 270px);
    }
    // 一等分移动端样式
    .oneEqualPartsMobile {
      height: 400px;
    }
  }
}
.textBlue {
  color: #1890ff;
}
</style>